package com.gxc.oauth2.service.impl;

import com.gxc.oauth2.repository.*;
import com.gxc.oauth2.entity.TbPermissionEntity;
import com.gxc.oauth2.entity.TbRolePermissionEntity;
import com.gxc.oauth2.entity.TbUserEntity;
import com.gxc.oauth2.entity.TbUserRoleEntity;
import com.gxc.oauth2.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author GongXincheng
 * @since 2019-10-11 17:41
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepository userRepository;
    @Resource
    private PermissionRepository permissionRepository;
    @Resource
    private RolePermissionRepository rolePermissionRepository;
    @Resource
    private UserRoleRepository userRoleRepository;

    @Override
    public TbUserEntity findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    @Override
    public List<TbPermissionEntity> getUserPermissionList(Long id) {
        List<TbUserRoleEntity> userRoleList = userRoleRepository.findByUserId(id);
        List<Long> roleIdList = userRoleList.stream().map(TbUserRoleEntity::getRoleId).collect(Collectors.toList());
        List<TbRolePermissionEntity> byRoleIdIn = rolePermissionRepository.findByRoleIdIn(roleIdList);
        List<Long> permissionList = byRoleIdIn.stream().map(TbRolePermissionEntity::getPermissionId).collect(Collectors.toList());
        return permissionRepository.findByIdIn(permissionList);
    }


}
